# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, request, jsonify, current_app, redirect, url_for, g

from application import db
from common.libs.UserSerivice import UserService
from web.models.user import User

route_user = Blueprint('user_page', __name__)


@route_user.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == "GET":
        return render_template("user/login.html")
    # 以下执行post请求代码
    resp = {"code": 200, "msg": "success", "data": {}}
    req = request.values
    # 输入的用户名
    login_name = req["login_name"] if "login_name" in req else ""
    # 输入的密码
    login_pwd = req["login_pwd"] if "login_pwd" in req else ""
    if (not login_name) or len(login_name) < 1:
        resp["code"] = -1
        resp["msg"] = "username error"
        return jsonify(resp)
    if (not login_pwd) or len(login_pwd) < 1:
        resp["code"] = -1
        resp["msg"] = "password error"
        return jsonify(resp)
    #【一】 访问数据库，验证用户信息
    user_info = User.query.filter_by(login_name=login_name).first()
    if not user_info:  # 数据库查不到
        resp["code"] = -1
        resp["msg"] = "请输入正确的用户名或密码"
        return jsonify(resp)
    # 用户名是正确的，则验证密码
    # 取得当前用户的盐值
    salt = user_info.login_salt # 不同的用户，加密的盐值是不同的
    gen_pwd = UserService.genPwd(login_pwd, salt)  # 跟注册时相同的加密机制
    if user_info.login_pwd != gen_pwd:
        resp["code"] = -1
        resp["msg"] = "密码错误"
        return jsonify(resp)
    # 密码也正确，登录成功
    # resp = {"code": 200, "msg": "success", "data": {}}
    resp['data']['username'] = login_name
    resp['data']['password'] = login_pwd

    # 【二】 把登录信息写入到cookies中，用以保存登录状态
    # return jsonify(resp) #无法携带cookie
    response = jsonify(resp)
    # 携带cookie，对cookie值加密
    cokie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
    response.set_cookie(current_app.config.get("AUTH_COOKIE_NAME"), cokie_str)
    return response


# 登出操作
@route_user.route("/logout")
def logout():
    response = redirect(url_for('user_page.login'))
    response.delete_cookie(current_app.config['AUTH_COOKIE_NAME'])
    return response

# 【编辑用户信息】
@route_user.route("/edit",methods=['GET','POST'])
def edit():
    if request.method=='GET':
        return render_template("user/edit.html")
    #以下是post请求的代码
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    req = request.values
    nickname = req["nickname"] if "nickname" in req else ""
    email = req["email"] if "email" in req else ""
    if (not nickname) or len(nickname) < 1:
        resp["code"] = -1
        resp["msg"] = "请输入符合规范的姓名"
        return jsonify(resp)
    if (not email) or len(email) < 1:
        resp["code"] = -1
        resp["msg"] = "请输入符合规范的邮箱"
        return jsonify(resp)
    # 修改当前登录人姓名和邮箱
    user_info = g.current_user
    user_info.nickname = nickname
    user_info.email = email
    # 提交到数据库
    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)


@route_user.route("/reset-pwd",methods=['GET','POST'])
def resetPwd():
    if request.method=='GET':
        return render_template("user/reset_pwd.html")
    #以下是post请求执行的代码
    resp = {"code": 200, "msg": "修改密码成功", "data": {}}
    req = request.values
    old_password = req["old_password"] if "old_password" in req else ""
    new_password = req["new_password"] if "new_password" in req else ""
    # 密码的格式检查
    if (not old_password) or len(old_password) < 1:
        resp["code"] = -1
        resp["msg"] = "请输入正确的原密码"
        return jsonify(resp)
    if (not new_password) or len(new_password) < 6:
        resp["code"] = -1
        resp["msg"] = "请输入不少于6位的新密码"
        return jsonify(resp)
    if old_password == new_password:
        resp["code"] = -1
        resp["msg"] = "新旧密码一致"
        return jsonify(resp)
    # 1.原密码检验
    # 通过g对象取得当前登录的用户对象
    user_info=g.current_user
    salt = user_info.login_salt # 取用户的盐值
    gen_pwd = UserService.genPwd(old_password, salt) # 跟注册时相同的加密机制
    if user_info.login_pwd != gen_pwd:
        resp["code"] = -1
        resp["msg"] = "原密码不对~"
        return jsonify(resp)
    # 原密码正确之后执行的代码
    # 2.

    user_info.login_pwd = UserService.genPwd(new_password, salt)
    # 提交到数据库
    db.session.add(user_info)
    db.session.commit()

    # 更新cookie
    # 3.生成新的cookie
    response = jsonify(resp)
    # 携带cookie
    cokie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
    response.set_cookie(current_app.config.get("AUTH_COOKIE_NAME"), cokie_str, max_age=7 * 24 * 60)
    return response


